/**
 * Copyright 2009-2011 xiaonei.com All right reserved.
 * This software is the confidential and proprietary information of Xiaonei.com ("Confidential Information"). 
 * You shall not disclose such Confidential Information and shall use it only in accordance with the terms of the license agreement you entered into with Xiaonei.com.
 * Create by XiaoNeiAntiSpamTeam
 *
 */

package com.xiaonei.testzookeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher.Event.KeeperState;

/**
 * @ClassName: AbstractZooKeeper
 * @Description: 抽象的ZooKeeper类
 * @author shaohui.liu shaohui.liu@opi-corp.com
 * @date Feb 22, 2010 6:12:54 PM
 * 
 */
public abstract class AbstractZooKeeper implements Watcher {

    private static final int SESSION_TIME = 2000;

    protected ZooKeeper zooKeeper;

    public AbstractZooKeeper(String hosts) {
        try {
            connect(hosts);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    protected CountDownLatch countDownLatch = new CountDownLatch(1);

    public void connect(String hosts) throws IOException, InterruptedException {
        zooKeeper = new ZooKeeper(hosts, SESSION_TIME, this);
        countDownLatch.await();
    }

    public void process(WatchedEvent event) {
        if (event.getState() == KeeperState.SyncConnected) {
            countDownLatch.countDown();
        }
    }

    public void close() throws InterruptedException {
        zooKeeper.close();
    }
}
